package com.mf.elephant.common.sso;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 登陆信息上下文
 * User: zhaoming
 * Date: 15-11-4
 * Time: 下午7:48
 * To change this template use File | Settings | File Templates.
 */
public class LoginContext {

    public static Logger logger = LoggerFactory.getLogger(LoginContext.class);

    private static ThreadLocal<LoginUser> local = new ThreadLocal<LoginUser>();

    public static LoginUser getLoginUser(){
        LoginUser loginUser = local.get();
        if(loginUser == null){
            try{
                Subject subject = SecurityUtils.getSubject();
                Session session = subject.getSession();
                loginUser = new LoginUser();
                loginUser.setUserId(Long.parseLong(session.getAttribute("userId").toString()));
                loginUser.setUserPortraitId(Long.parseLong(session.getAttribute("userPortraitId").toString()));
                loginUser.setUserCode(session.getAttribute("userCode").toString());
                loginUser.setUserName(session.getAttribute("userName").toString());
                loginUser.setLoginType(session.getAttribute("loginType").toString());
                LoginContext.setLoginUser(loginUser);
            }catch (Exception e){
                logger.info("用户session失效,请重新登陆.");
            }

        }
        return loginUser;
    }

    public static void setLoginUser(LoginUser loginUser) {
        local.set(loginUser);
    }

    public static void removeLoginUser(){
        local.remove();
    }

}
